import { post } from '../../utils/http'
import { isEmptyForTrim } from '../../utils/util'

Page({
  data: {
    form: { username: '', password: '' }
  },

  updateForm (e) {
    const { detail, target } = e
    const key = target.dataset.field
    this.setData({
      [`form.${key}`]: detail.value
    })
  },

  userLogin () {
    if (isEmptyForTrim(this.data.form.username)) {
      return wx.showToast({ title: '请填写用户名' })
    }
    wx.showLoading({ mask: true, title: '登录中...' })
    post({
      url: '/api/portal/login',
      data: this.data.form
    }).then(async () => {
      await wx.hideLoading()
      wx.switchTab({
        url: '../home/index',
      })
    }).catch(() => {
      wx.hideLoading()
    })
  },

  goRegister () {
    wx.redirectTo({
      url: '/pages/register/index',
    })
  }
})
